package org.javaexpert.spaces.masterworker;

import net.jini.core.entry.Entry;
import net.jini.core.lease.Lease;
import net.jini.space.JavaSpace;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.util.concurrent.*;

class TaskBagFuture<T> implements Future<T> {
    private final Long taskId;
    private JavaSpace space;
    private boolean done = false;
    private TaskBag taskBag;

    public TaskBagFuture(Long taskId, Callable<T> callable, JavaSpace space, TaskBag taskBag) {
        assert taskId != null;
        assert callable != null;

        this.taskBag = taskBag;
        this.taskId = taskId;
        this.space = space;
    }

    public boolean cancel(boolean b) {
        throw new NotImplementedException();
    }

    public boolean isCancelled() {
        throw new NotImplementedException();
    }

    public boolean isDone() {
        if (!done) {
            done = read(new TaskBag.TaskResultEntry(taskId), Lease.FOREVER) != null;
        }
        return done;
    }

    public T get() throws InterruptedException, ExecutionException {
        return (T) taskBag.consumeTaskResult(taskId);
    }


    public T get(long l, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
        throw new NotImplementedException();
    }

    private Entry read(Entry template, long lease) {
        try {
            return space.read(template, null, lease);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
